class Student:
    def __init__(self, student_id, name):
        self.student_id = student_id
        self.name = name
        self.grades = {}  # {course: (score, credits)}
        self.moral_grade = "合格"
        self.cet4_score = 0
        self.physical_test = "合格"
        self.physical_score = 0  # 体育成绩
        self.additional_points = 0  # 额外加分

    def add_grade(self, course, score, credits):
        self.grades[course] = (score, credits)

    def modify_grade(self, course, score, credits):
        if course in self.grades:
            self.grades[course] = (score, credits)

    def delete_grade(self, course):
        if course in self.grades:
            del self.grades[course]

    def calculate_gpa(self):
        total_credits = sum(credits for score, credits in self.grades.values())
        total_points = sum(
            (0 if score < 60 else 1 + (score - 60) / 10) * credits for score, credits in self.grades.values())
        return total_points / total_credits if total_credits > 0 else 0

    def is_scholarship_eligible(self):
        gpa = self.calculate_gpa()
        if gpa >= 3.6 and self.cet4_score >= 425 and self.physical_test == "合格":
            return "一等奖学金"
        elif gpa >= 3.2:
            return "二等奖学金"
        elif gpa >= 2.8:
            return "三等奖学金"
        return None

    def is_three_good_student(self):
        gpa = self.calculate_gpa()
        if gpa >= 3.6 and self.physical_score >= 75 and self.cet4_score >= 425:
            return True
        return False

    def __str__(self):
        grades_str = ','.join(f"{course}:{score}:{credits}" for course, (score, credits) in self.grades.items())
        return f"{self.student_id}|{self.name}|{self.moral_grade}|{self.cet4_score}|{self.physical_test}|{self.physical_score}|{self.additional_points}|{grades_str}"

    @staticmethod
    def from_str(data_str):
        parts = data_str.strip().split('|')
        student = Student(parts[0], parts[1])
        student.moral_grade = parts[2]
        student.cet4_score = int(parts[3])
        student.physical_test = parts[4]
        student.physical_score = int(parts[5])
        student.additional_points = float(parts[6])
        if len(parts) > 7 and parts[7]:
            grades = parts[7].split(',')
            for grade in grades:
                course, score, credits = grade.split(':')
                student.grades[course] = (float(score), float(credits))
        return student


students = []


def load_data():
    global students
    try:
        with open('students.txt', 'r') as f:
            students = [Student.from_str(line) for line in f.readlines()]
    except FileNotFoundError:
        students = []


def save_data():
    with open('students.txt', 'w') as f:
        for student in students:
            f.write(str(student) + '\n')


def add_student():
    student_id = input("请输入学生学号: ")
    name = input("请输入学生姓名: ")
    student = Student(student_id, name)
    students.append(student)
    save_data()
    print(f"学生 {name} 添加成功")


def modify_student():
    student_id = input("请输入要修改的学生学号: ")
    for student in students:
        if student.student_id == student_id:
            name = input(f"请输入新的学生姓名(当前: {student.name}): ")
            student.name = name
            student.moral_grade = input(f"请输入新的品德评定(当前: {student.moral_grade}): ")
            student.cet4_score = int(input(f"请输入新的英语四级成绩(当前: {student.cet4_score}): "))
            student.physical_test = input(f"请输入新的体育测试结果(当前: {student.physical_test}): ")
            student.physical_score = int(input(f"请输入新的体育成绩(当前: {student.physical_score}): "))
            student.additional_points = float(input(f"请输入新的额外加分(当前: {student.additional_points}): "))
            save_data()
            print(f"学生 {student_id} 信息修改成功")
            return
    print("未找到该学生")


def delete_student():
    student_id = input("请输入要删除的学生学号: ")
    global students
    students = [student for student in students if student.student_id != student_id]
    save_data()
    print(f"学生 {student_id} 删除成功")


def add_grade():
    student_id = input("请输入学生学号: ")
    course = input("请输入课程名称: ")
    score = float(input("请输入成绩: "))
    credits = float(input("请输入学分: "))
    for student in students:
        if student.student_id == student_id:
            student.add_grade(course, score, credits)
            save_data()
            print(f"课程 {course} 的成绩添加成功, 当前GPA: {student.calculate_gpa():.2f}")
            return
    print("未找到该学生")


def modify_grade():
    student_id = input("请输入学生学号: ")
    course = input("请输入课程名称: ")
    score = float(input("请输入成绩: "))
    credits = float(input("请输入学分: "))
    for student in students:
        if student.student_id == student_id:
            student.modify_grade(course, score, credits)
            save_data()
            print(f"课程 {course} 的成绩修改成功, 当前GPA: {student.calculate_gpa():.2f}")
            return
    print("未找到该学生")


def delete_grade():
    student_id = input("请输入学生学号: ")
    course = input("请输入课程名称: ")
    for student in students:
        if student.student_id == student_id:
            student.delete_grade(course)
            save_data()
            print(f"课程 {course} 的成绩删除成功, 当前GPA: {student.calculate_gpa():.2f}")
            return
    print("未找到该学生")


def evaluate_scholarships():
    print("\n评定奖学金结果:")
    for student in students:
        scholarship = student.is_scholarship_eligible()
        if scholarship:
            print(f"学生 {student.name} 获得 {scholarship}")
        else:
            print(f"学生 {student.name} 未获得奖学金")


def evaluate_three_good_students():
    print("\n评选三好学生结果:")
    for student in students:
        if student.is_three_good_student():
            print(f"学生 {student.name} 被评为三好学生")
        else:
            print(f"学生 {student.name} 未被评为三好学生")


def add_additional_points():
    student_id = input("请输入学生学号: ")
    points = float(input("请输入额外加分: "))
    for student in students:
        if student.student_id == student_id:
            student.additional_points += points
            save_data()
            print(f"学生 {student.name} 的额外加分 {points} 添加成功")
            return
    print("未找到该学生")


def query_student_by_id():
    student_id = input("请输入学生学号: ")
    for student in students:
        if student.student_id == student_id:
            print(f"\n学号: {student.student_id}")
            print(f"姓名: {student.name}")
            print(f"成绩: {student.grades}")
            print(f"英语四级成绩: {student.cet4_score}")
            print(f"体育成绩: {student.physical_score}")
            print(f"额外加分: {student.additional_points}\n")
            return
    print("未找到该学生")


def query_student_by_name():
    name = input("请输入学生姓名: ")
    for student in students:
        if student.name == name:
            print(f"\n学号: {student.student_id}")
            print(f"姓名: {student.name}")
            print(f"成绩: {student.grades}")
            print(f"英语四级成绩: {student.cet4_score}")
            print(f"体育成绩: {student.physical_score}")
            print(f"额外加分: {student.additional_points}\n")
            return
    print("未找到该学生")


def query_all_students():
    if not students:
        print("没有学生信息")
    else:
        for student in students:
            print(f"\n学号: {student.student_id}")
            print(f"姓名: {student.name}")
            print(f"成绩: {student.grades}")
            print(f"英语四级成绩: {student.cet4_score}")
            print(f"体育成绩: {student.physical_score}")
            print(f"额外加分: {student.additional_points}\n")


def query_scholarship_students():
    print("\n奖学金获得名单:")
    for student in students:
        scholarship = student.is_scholarship_eligible()
        if scholarship:
            print(f"学生 {student.name} 获得 {scholarship}")


def query_three_good_students():
    print("\n三好学生名单:")
    for student in students:
        if student.is_three_good_student():
            print(f"学生 {student.name} 被评为三好学生")


def sort_students_by_gpa():
    sorted_students = sorted(students, key=lambda x: x.calculate_gpa(), reverse=True)
    print("\n按GPA排序结果:")
    for student in sorted_students:
        print(f"学号: {student.student_id}, 姓名: {student.name}, GPA: {student.calculate_gpa():.2f}")


def sort_students_by_id():
    sorted_students = sorted(students, key=lambda x: x.student_id)
    print("\n按学号排序结果:")
    for student in sorted_students:
        print(f"学号: {student.student_id}, 姓名: {student.name}")


def main():
    load_data()
    while True:
        print("\n学生成绩管理系统")
        print("1. 学生管理")
        print("2. 成绩管理")
        print("3. 评定管理")
        print("4. 查询管理")
        print("0. 退出")
        choice = input("请选择操作: ")
        if choice == '1':
            student_management()
        elif choice == '2':
            grade_management()
        elif choice == '3':
            evaluation_management()
        elif choice == '4':
            query_management()
        elif choice == '0':
            save_data()
            break
        else:
            print("无效的选择，请重新输入")


def student_management():
    while True:
        print("\n学生管理")
        print("1. 添加学生")
        print("2. 修改学生")
        print("3. 删除学生")
        print("4. 返回主菜单")
        choice = input("请选择操作: ")
        if choice == '1':
            add_student()
        elif choice == '2':
            modify_student()
        elif choice == '3':
            delete_student()
        elif choice == '4':
            break
        else:
            print("无效的选择，请重新输入")


def grade_management():
    while True:
        print("\n成绩管理")
        print("1. 添加成绩")
        print("2. 修改成绩")
        print("3. 删除成绩")
        print("4. 添加额外加分")
        print("5. 返回主菜单")
        choice = input("请选择操作: ")
        if choice == '1':
            add_grade()
        elif choice == '2':
            modify_grade()
        elif choice == '3':
            delete_grade()
        elif choice == '4':
            add_additional_points()
        elif choice == '5':
            break
        else:
            print("无效的选择，请重新输入")


def evaluation_management():
    while True:
        print("\n评定管理")
        print("1. 评定奖学金")
        print("2. 评选三好学生")
        print("3. 查询奖学金获得名单")
        print("4. 查询三好学生名单")
        print("5. 返回主菜单")
        choice = input("请选择操作: ")
        if choice == '1':
            evaluate_scholarships()
        elif choice == '2':
            evaluate_three_good_students()
        elif choice == '3':
            query_scholarship_students()
        elif choice == '4':
            query_three_good_students()
        elif choice == '5':
            break
        else:
            print("无效的选择，请重新输入")


def query_management():
    while True:
        print("\n查询管理")
        print("1. 查询学生信息（按学号）")
        print("2. 查询学生信息（按姓名）")
        print("3. 查询所有学生信息")
        print("4. 按GPA排序")
        print("5. 按学号排序")
        print("6. 返回主菜单")
        choice = input("请选择操作: ")
        if choice == '1':
            query_student_by_id()
        elif choice == '2':
            query_student_by_name()
        elif choice == '3':
            query_all_students()
        elif choice == '4':
            sort_students_by_gpa()
        elif choice == '5':
            sort_students_by_id()
        elif choice == '6':
            break
        else:
            print("无效的选择，请重新输入")


if __name__ == "__main__":
    main()
